<?php

/*
info: 公共函数库
date: 2011-12-19
*/

if (!defined('WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

if (defined('GLOBAL_FUNC'))
{
	return;
}
define('GLOBAL_FUNC', TRUE);

//生成安全字符串
function global_Addslashes($string, $force = 0)
{
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if (!MAGIC_QUOTES_GPC || $force)
	{
		if (is_array($string))
		{
			foreach ($string as $key => $val)
			{
				$string[$key] = global_Addslashes($val, $force);
			}
		}
		else
		{
			$string = trim(addslashes($string));
		}
	}
	else
	{
		$string = global_Trim($string);
	}
	return $string;
}

//检查是否来自本站
function global_CheckCome()
{
	global $webserver;
	if ($webserver['comeurl']!='' && $webserver['webhost']!='')
	{
		if (global_FormatHost($webserver['comeurl'])==$webserver['webhost'])
		{
			return TRUE;
		}
	}
	return FALSE;
}

//检查是否字符串中含有某个字符
function global_CheckHaveVar($strall, $strone, $strcomm = ',')
{
	return strstr($strcomm.$strall.$strcomm, $strcomm.$strone.$strcomm) ? TRUE : FALSE;
}

//检查身份证号码
function global_CheckIdCard($stridcard, $straddress='', $strbirthday = '', $intsex = 0)
{
	$stridcard = strtoupper($stridcard);
	if (!preg_match('/^(\d{15}|\d{17}(\d|X))$/', $stridcard))
	{
		return FALSE;
	}
	$tempaddrnum = substr($stridcard, 0, 6);
	if (strlen($stridcard)==15)
	{
		$tempbirthday = array((in_array(substr($stridcard, 12, 3), array('996', '997', '998', '999')) ? '18' : '19').substr($stridcard, 6, 2), substr($stridcard, 8, 2), substr($stridcard, 10, 2));
		$tempsex = substr($stridcard, -1, 1);
		$tempcheck = '';
	}
	else
	{
		$tempbirthday = array(substr($stridcard, 6, 4), substr($stridcard, 10, 2), substr($stridcard, 12, 2));
		$tempsex = substr($stridcard, -2, 1);
		$tempcheck = substr($stridcard, -1, 1);
	}
	if (!global_IsDate(implode('-', $tempbirthday)))
	{
		return FALSE;
	}
	if ($strbirthday != '')
	{
		if (!global_IsDate($strbirthday))
		{
			return FALSE;
		}
		$arybirthday = explode('-', $strbirthday);
		if (intval($arybirthday[0])!=intval($tempbirthday[0]) || intval($arybirthday[1])!=intval($tempbirthday[1]) || intval($arybirthday[2])!=intval($tempbirthday[2]))
		{
			return FALSE;
		}
	}
	if ($intsex>0 && intval($tempsex%2)!=intval($intsex%2))
	{
		return FALSE;
	}
	if ($tempcheck != '')
	{
		//加权因子
		$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
		//校验码对应值
		$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
		$checksum = 0;
		for ($i = 0; $i<17; $i++)
		{
			$checksum += substr($stridcard, $i, 1) * $factor[$i];
		}
		$mod = $checksum % 11;
		$verify_number = $verify_number_list[$mod];
		if ($tempcheck != $verify_number)
		{
			return FALSE;
		}
	}
	return TRUE;
}

//检查是否全不为空
function global_CheckNotEmpty($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			if (!global_CheckNotEmpty($val))
			{
				return FALSE;
			}
		}
	}
	else
	{
		if (trim($string)=='')
		{
			return FALSE;
		}
	}
	return TRUE;
}

//检查密码是否合法
function global_CheckPassword($strpass)
{
	//!preg_match('/^[0-9]{6,}$/', $strpass)
	if (strlen($strpass)>=6)
	{
		return TRUE;
	}
	return FALSE;
}

/*
 * 检查提交数据格式
 * $arySet 设定检查格式数组 array(
									0 => '表单变量名[加方括号“[]”表示数组],非数组情况下可增加“,字段名”来设置数据库字段', 
									1 => '要求类型',
									2 => '额外判断表达式[@代表变量]',
									3 => '提示错误消息[为空且非必填且有默认值就用默认值填充变量]',
									4 => '是否必填[默认0:否]',
									5 => '设定默认值[默认无，数组的默认值为单个key的默认值]'
								)
 * $isStop 是否检测到不符合条件的就停止
 * $strParam 将表单参数数组保存在webglobal的该变量下，默认保存在$webglobal['CPP']，方便用于程序后续调用
 * $strData 将表单有字段名的参数数组保存在webglobal的该变量下，默认保存在$webglobal['CPD']，用于直接写入数据库
 * $strMsg 将错误信息数组保存在webglobal的该变量下，默认保存在$webglobal['CPM']，可以通过判断该值是否为空来确定执行结果
 * return bool 是否全部校验通过
 */
function global_CheckPost($arySet, $isStop = FALSE, $strParam = 'CPP', $strData = 'CPD', $strMsg = 'CPM')
{
	global $webglobal, $webrequest;
	$tempReturn = TRUE;
	$webglobal[$strParam] = $webglobal[$strData] = $webglobal[$strMsg] = array();
	$format = array(
						/* 类型标记 => array(正则规则或者额外判断函数[@代表变量], 格式化语句[@代表变量]) */
						'int' => array('/^(-?[1-9][0-9]*|0)$/', 'intval(@)'),		//整数
						'num' => array('is_numeric(@)', 'floatval(@)'),			//数字
						'bool' => array('', 'global_ConvBool(@)'),				//取值为0或者1
						'str' => array('', 'global_ConvHtml(trim(@))'),			//去掉首尾空白和转换html的字符
						'url' => array('', 'global_ConvUrl(@)'),				//URL地址
						'email' => array('global_IsEmail(@)', ''),				//email地址
						'mobile' => array('global_IsMobile(@)', ''),			//手机
						'date' => array('global_IsDate(@)', ''),				//“年-月-日”格式
						'username' => array('global_CheckUsername(@)', ''),		//用户名格式
						'password' => array('global_CheckPassword(@)', ''),		//密码格式
						'chinese' => array('/^[\x{4e00}-\x{9fa5}]+$/u', ''),	//UFT8中文格式
						'idcard' => array('global_CheckIdCard(@)', ''),			//身份证号码
				   );
	foreach ($arySet as $tempParamSet)
	{
		//数组处理
		if (substr($tempParamSet[0], -2)=='[]')
		{
			$tempkey = substr($tempParamSet[0], 0, -2);
			//数组参数不存在
			if (!isset($webrequest[$tempkey]))
			{
				//必填
				if (isset($tempParamSet[4]) && $tempParamSet[4])
				{
					$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
					$tempReturn = FALSE;
					if ($isStop)
					{
						return $tempReturn;
					}
				}
				elseif (isset($tempParamSet[5]))
				{
					$webglobal[$strParam][$tempkey] = array($tempParamSet[5]);
				}
				continue;
			}
			else
			{
				//不是数组格式转化
				if (!is_array($webrequest[$tempkey]))
				{
					$webrequest[$tempkey] = array($webrequest[$tempkey]);
				}
				foreach ($webrequest[$tempkey] as $tempk => $tempv)
				{
					$tempk = intval($tempk);
					$tempoldv = $tempv;
					//存在校验格式检查
					if (isset($format[$tempParamSet[1]]))
					{
						//有校验规则 必填或值不为空
						if (!empty($format[$tempParamSet[1]][0]) && ((isset($tempParamSet[4]) && $tempParamSet[4]) || $tempv!=''))
						{
							//正则规则判定
							if (substr($format[$tempParamSet[1]][0], 0, 1)=='/')
							{
								$tempStatus = preg_match($format[$tempParamSet[1]][0], $tempv);
							}
							//语法判断
							else
							{
								eval('$tempStatus = ('.str_replace('@', '$tempv', $format[$tempParamSet[1]][0]).');');
							}
							if (!$tempStatus)
							{
								//非必填有默认值提示消息为空
								if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
								{
									$webglobal[$strParam][$tempkey][$tempk] = $tempParamSet[5];
								}
								else
								{
									$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
									$tempReturn = FALSE;
									if ($isStop)
									{
										return $tempReturn;
									}
								}
								continue;
							}
						}
						//有格式化函数
						if (!empty($format[$tempParamSet[1]][1]))
						{
							eval('$tempv = '.str_replace('@', '$tempv', $format[$tempParamSet[1]][1]).';');
						}
					}
					//值为空处理
					if ($tempoldv==='' || $tempv==='')
					{
						//必填报错
						if (isset($tempParamSet[4]) && $tempParamSet[4])
						{
							$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
							$tempReturn = FALSE;
							if ($isStop)
							{
								return $tempReturn;
							}
						}
						else
						{
							//值为空有默认值就赋默认值否则就用格式化的值
							$webglobal[$strParam][$tempkey][$tempk] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						}
						continue;
					}
					//额外判定条件
					if (isset($tempParamSet[2]) && !empty($tempParamSet[2]))
					{
						eval('$tempStatus = ('.str_replace('@', '$tempv', $tempParamSet[2]).');');
						if (!$tempStatus)
						{
							//非必填有默认值提示消息为空
							if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
							{
								$webglobal[$strParam][$tempkey][$tempk] = $tempParamSet[5];
							}
							else
							{
								$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
								$tempReturn = FALSE;
								if ($isStop)
								{
									return $tempReturn;
								}
							}
							continue;
						}
					}
					$webglobal[$strParam][$tempkey][$tempk] = $tempv;
				}
			}
		}
		//普通变量处理
		else
		{
			@list($tempkey, $tempdatakey) = explode(',', $tempParamSet[0]);
			//兼容获取变量名和数据库变量名一样时使用“,”即可
			if (!is_null($tempdatakey) && $tempdatakey==='')
			{
				$tempdatakey = $tempkey;
			}
			if (!isset($webrequest[$tempkey]))
			{
				//必填
				if (isset($tempParamSet[4]) && $tempParamSet[4])
				{
					$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
					$tempReturn = FALSE;
					if ($isStop)
					{
						return $tempReturn;
					}
				}
				elseif (isset($tempParamSet[5]))
				{
					$webglobal[$strParam][$tempkey] = $tempParamSet[5];
					if (!empty($tempdatakey))
					{
						$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
					}
				}
				continue;
			}
			else
			{
				$tempv = $tempoldv = $webrequest[$tempkey];
				if (isset($format[$tempParamSet[1]]))
				{
					//有校验规则 必填或值不为空
					if (!empty($format[$tempParamSet[1]][0]) && ((isset($tempParamSet[4]) && $tempParamSet[4]) || $tempv!=''))
					{
						//正则规则判定
						if (substr($format[$tempParamSet[1]][0], 0, 1)=='/')
						{
							$tempStatus = preg_match($format[$tempParamSet[1]][0], $tempv);
						}
						//语法判断
						else
						{
							eval('$tempStatus = ('.str_replace('@', '$tempv', $format[$tempParamSet[1]][0]).');');
						}
						if (!$tempStatus)
						{
							//非必填有默认值提示消息为空
							if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
							{
								$webglobal[$strParam][$tempkey] = $tempParamSet[5];
								if (!empty($tempdatakey))
								{
									$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
								}
							}
							else
							{
								$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
								$tempReturn = FALSE;
								if ($isStop)
								{
									return $tempReturn;
								}
							}
							continue;
						}
					}
					//有格式化函数
					if (!empty($format[$tempParamSet[1]][1]))
					{
						eval('$tempv = '.str_replace('@', '$tempv', $format[$tempParamSet[1]][1]).';');
					}
				}
				//值为空处理
				if ($tempoldv==='' || $tempv==='')
				{
					//必填报错
					if (isset($tempParamSet[4]) && $tempParamSet[4])
					{
						$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
						$tempReturn = FALSE;
						if ($isStop)
						{
							return $tempReturn;
						}
					}
					else
					{
						//值为空有默认值就赋默认值否则就用格式化的值
						$webglobal[$strParam][$tempkey] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						if (!empty($tempdatakey))
						{
							$webglobal[$strData][$tempdatakey] = isset($tempParamSet[5]) ? $tempParamSet[5] : $tempv;
						}
					}
					continue;
				}
				//额外判定条件
				if (isset($tempParamSet[2]) && !empty($tempParamSet[2]))
				{
					eval('$tempStatus = ('.str_replace('@', '$tempv', $tempParamSet[2]).');');
					if (!$tempStatus)
					{
						//非必填有默认值提示消息为空
						if (isset($tempParamSet[5]) && !$tempParamSet[4] && empty($tempParamSet[3]))
						{
							$webglobal[$strParam][$tempkey] = $tempParamSet[5];
							if (!empty($tempdatakey))
							{
								$webglobal[$strData][$tempdatakey] = $tempParamSet[5];
							}
						}
						else
						{
							$webglobal[$strMsg][$tempkey] = $tempParamSet[3];
							$tempReturn = FALSE;
							if ($isStop)
							{
								return $tempReturn;
							}
						}
						continue;
					}
				}
				$webglobal[$strParam][$tempkey] = $tempv;
				if (!empty($tempdatakey))
				{
					$webglobal[$strData][$tempdatakey] = $tempv;
				}
			}
		}
	}
	return $tempReturn;
}

//检测字符串格式
//$inttype 检测类型 0:字母和数字 1:字母和数字且首字符为字母 2:字母 3:数字
//$intmode 检测模式 0:不区分大小写 1:小写 2:大写
//$intminlen 最小长度  $intmaxlen 最大长度
function global_CheckString($string, $inttype = 0, $intmode = 0, $intminlen = 0, $intmaxlen = 0)
{
	$pattern = '/^';
	switch ($intmode)
	{
	case 1:
		$tempsign = 'a-z';
		break;
	case 2:
		$tempsign = 'A-Z';
		break;
	default:
		$tempsign = 'a-zA-Z';
	}
	switch ($inttype)
	{
	case 1:
		$pattern .= '['.$tempsign.']{1}['.$tempsign.'0-9]';
		break;
	case 2:
		$pattern .= '['.$tempsign.']';
		break;
	case 3:
		$pattern .= '[0-9]';
		break;
	default:
		$pattern .= '['.$tempsign.'0-9]';
	}
	if ($intminlen<=0)
	{
		$pattern .= '*';
	}
	else
	{
		$tempminlen = ($inttype==1) ? $intminlen-1 : $intminlen;
		$pattern .= '{'.$tempminlen.',';
		if ($intmaxlen>=$intminlen)
		{
			$tempmaxlen = ($inttype==1) ? $intmaxlen-1 : $intmaxlen;
			$pattern .= $tempmaxlen;
		}
		$pattern .= '}';
	}
	$pattern .= '$/';
	echo $pattern;
	if (preg_match($pattern, $string))
	{
		return TRUE;
	}
	return FALSE;
}

//检查是否点击提交按钮
function global_CheckSubmit($strvar, $allowget = 0)
{
	global $webrequest, $_SERVER;
	if (!empty($webrequest[$strvar]) && ($allowget || ($_SERVER['REQUEST_METHOD']=='POST' && global_CheckCome())))
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

//检查用户名是否合法
function global_CheckUsername($strname)
{
	if (preg_match('/^[a-z]{1}[a-z0-9]{3,14}$/', $strname))
	{
		return TRUE;
	}
	return FALSE;
}

//清除cookie
function global_ClearCookie($var, $prefix = 1)
{
	global_SetCookie($var, '', -86400*365, $prefix);
}

//连接数据库
function global_ConnectDB()
{
	global $db, $webconfig;
	if (!is_object($db))
	{
		$db = new MysqlDB;
		$db->Connect($webconfig['dbhost'], $webconfig['dbuser'], $webconfig['dbpass'], $webconfig['dbname'], $webconfig['dbpconnect']);
		unset($GLOBALS['webconfig']['dbhost'], $GLOBALS['webconfig']['dbuser'], $GLOBALS['webconfig']['dbpass'], $GLOBALS['webconfig']['dbname'], $GLOBALS['webconfig']['dbpconnect']);
	}
}

//转换0，1状态
function global_ConvBool($intnum)
{
	return (intval(trim($intnum)) > 0) ? 1 : 0;
}

//转换email地址
function global_ConvEmail($email, $tolink = 1)
{
	$email = str_replace(array('@', '.'), array('&#64;', '&#46;'), $email);
	return $tolink ? '<a href="mailto: '.$email.'">'.$email.'</a>': $email;
}

//将字符中的HTML标识转换
function global_ConvHtml($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_ConvHtml($val);
		}
	}
	else
	{
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '\'', '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), trim($string)));
	}
	return $string;
}

//转换换行符为HTML代码
//$intp 两次换行转换为P标签 0:否 1:是
function global_ConvNewline($string, $intp = 0)
{
	$returnstr = '';
	if (trim($string)!='')
	{
		$returnstr = str_replace(array("\r\n", "\r", "\n"), '<br />', $string);
		if ($intp > 0)
		{
			$returnstr = '<p>'.$returnstr.'</p>';
			if (strpos($returnstr, '<br /><br />')!==FALSE)
			{
				$returnstr = str_replace('<br /><br />', '</p><p>', $returnstr);
				$returnstr = str_replace('<p><br />', '<p class="noindent">', $returnstr);
				$returnstr = str_replace('<p></p>', '', $returnstr);
			}
		}
	}
	return $returnstr;
}

//转换字符或数字时间为数字
function global_ConvTime($mixVar, $zone = 999)
{
	global $webserver;
	if ($zone == 999)
	{
		$zone = defined('WEBTIMEZONE') ? WEBTIMEZONE : 8;
	}
	$tempReturNnum = 0;
	if (is_array($mixVar))
	{
		$tempSetArray = explode('-', global_FormatTime($webserver['timestamp'], 'H-i-s-m-d-Y'));
		$tempSetArray = array('hour' => $tempSetArray[0], 'minute' => $tempSetArray[1], 'second' => $tempSetArray[2], 'month' => $tempSetArray[3], 'day' => $tempSetArray[4], 'year' => $tempSetArray[5]);
		$tempSetArray = array_merge($tempSetArray, $mixVar);
		$tempReturNnum = mktime($tempSetArray['hour'], $tempSetArray['minute'], $tempSetArray['second'], $tempSetArray['month'], $tempSetArray['day'], $tempSetArray['year']);
	}
	else
	{
		$tempReturNnum = strtotime($mixVar);
	}
	return $tempReturNnum - $zone * 3600 + date('Z');
}

//转换URL地址
function global_ConvUrl($strurl)
{
	$returnstr = '';
	if (trim($strurl)!='')
	{
		$returnstr = global_ConvHtml(preg_match("/^https?:\/\/.+/i", $strurl) ? $strurl : 'http://'.$strurl);
	}
	return $returnstr;
}

//递归建立文件夹
function global_CreateFolder($strfolder)
{
	if (!is_dir($strfolder))
	{
		$strfolder = preg_replace("/^".preg_quote(WEBFILEPATH, '/')."\//", "", $strfolder);
		$folderarray = explode('/', $strfolder);
		$mkfolder = WEBFILEPATH;
		foreach ($folderarray as $tempfolder)
		{
			$tempfolder = trim($tempfolder);
			if (empty($tempfolder))
			{
				continue;
			}
			$mkfolder .= '/'.$tempfolder;
			if (!is_dir($mkfolder))
			{
				if (!@mkdir($mkfolder, 0777))
				{
					return FALSE;
				}
				@touch($mkfolder.'/index.htm');
			}
		}
	}
	return TRUE;
}

//截取字符串
function global_CutStr($strVar, $intLength, $strDot = '...')
{
	$strVarLength = strlen($strVar);
	$strDotLength = strlen($strDot);
	if ($strVarLength <= $intLength)
	{
		return $strVar;
	}

	$strVar = str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $strVar);
	$strcut = '';
	$n = $tn = $noc = 0;
	while ($n<$strVarLength && isset($strVar[$n]))
	{
		$t = ord($strVar[$n]);
		if ($t==9 || $t==10 || ($t>=32 && $t<=126))
		{
			$tn = 1; $n++; $noc++;
		}
		elseif ($t>=194 && $t<=223)
		{
			$tn = 2; $n += 2; $noc += 2;
		}
		elseif ($t>=224 && $t<239)
		{
			$tn = 3; $n += 3; $noc += 2;
		}
		elseif ($t>=240 && $t<=247)
		{
			$tn = 4; $n += 4; $noc += 2;
		}
		elseif ($t>=248 && $t<=251)
		{
			$tn = 5; $n += 5; $noc += 2;
		}
		elseif ($t==252 || $t==253)
		{
			$tn = 6; $n += 6; $noc += 2;
		}
		else
		{
			$n++;
		}

		if ($noc >= $intLength-$strDotLength)
		{
			break;
		}
	}
	if ($noc > $intLength-$strDotLength)
	{
		$n -= $tn;
	}
	$strcut = substr($strVar, 0, $n);
	$strcut = str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$strDot;
}

function global_CutStrR($str, $slen, $startdd='') {
	$str = global_CutStr(stripslashes($str), $slen, $startdd);
	return addslashes($str);
}

function SpHtml2Text($str)
{
	$str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU","",$str);
	$alltext = "";
	$start = 1;
	for($i=0;$i<strlen($str);$i++)
	{
		if($start==0 && $str[$i]==">")
		{
			$start = 1;
		}
		else if($start==1)
		{
			if($str[$i]=="<")
			{
				$start = 0;
				$alltext .= " ";
			}
			else if(ord($str[$i])>31)
			{
				$alltext .= $str[$i];
			}
		}
	}
	$alltext = str_replace("　"," ",$alltext);
	$alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
	$alltext = preg_replace("/[ ]+/s"," ",$alltext);
	return $alltext;
}

function AddDay($ntime, $aday) {
	$dayst = 3600 * 24;
	$oktime = $ntime + ($aday * $dayst);
	return $oktime;
}

//获取debug信息
function global_DebugInfo()
{
	global $db, $webserver;
	$webserver['endmtime'] = explode(' ', microtime());
	$querynumcount = is_object($db) ? $db->querynum : 0;
	$webserver['debuginfo'] = array('time' => number_format(($webserver['endmtime'][1]+$webserver['endmtime'][0]-$webserver['beginmtime'][1]-$webserver['beginmtime'][0]), 6), 'queries' => $querynumcount);
	return TRUE;
}

//解密函数
function global_DecryptKey($txt, $authkey)
{
	$txt = global_Key(base64_decode(str_replace(array(',', '_', '.'), array('+', '/', '='), $txt)), $authkey);
	$txtlen = strlen($txt);
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		$md5 = substr($txt, $i, 1);
		$i++;
		$tmp .= (substr($txt, $i, 1) ^ $md5);
	}
	return $tmp;
}

//加密函数
function global_EncryptKey($txt, $authkey)
{
	srand((double)microtime()*1000000);
	$encryptkey = md5(rand(0,32000));
	$encryptkeylen = strlen($encryptkey);
	$txtlen = strlen($txt);
	$ctr = 0;
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		if ($ctr == $encryptkeylen)
		{
			$ctr = 0;
		}
		$tmp .= substr($encryptkey, $ctr, 1).(substr($txt, $i, 1) ^ substr($encryptkey, $ctr, 1));
		$ctr++;
	}
	return str_replace(array('+', '/', '='), array(',', '_', '.'), base64_encode(global_Key($tmp, $authkey)));
}

//获取文件后缀名
function global_FileExt($filename, $clearsuffix = 1)
{
	if ($clearsuffix > 0)
	{
		$filename = preg_replace("/^(.+)\.file$/i", "\\1", $filename);	//剔掉危险文件新加的后缀
	}
	$fileext = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
	if (!preg_match('/^[a-z0-9]{1,10}$/', $fileext))
	{
		$fileext = '';
	}
	return $fileext;
}

//格式化文件大小
function global_FileSize($filesize)
{
	if ($filesize >= 1073741824)
	{
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	}
	elseif ($filesize >= 1048576)
	{
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	}
	elseif ($filesize >= 1024)
	{
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	}
	else
	{
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

//格式化主机地址
function global_FormatHost($strurl)
{
	$strurl = preg_replace("/^(https?:\/\/)?(.+?)(\/.*)?$/i", "\\2", $strurl);
	return $strurl;
}

//格式化时间
function global_FormatTime($timenum, $mode = 'FS', $zone = 999)
{
	global $webserver;
	if ($zone == 999)
	{
		$zone = defined('WEBTIMEZONE') ? WEBTIMEZONE : 8;
	}
	if ($timenum<=0)
	{
		$timenum = $webserver['timestamp'];
	}
	switch (strtoupper($mode))
	{
		case 'FT':	$mode = (global_FormatTime($timenum,'FD')==global_FormatTime($webserver['timestamp'],'FD')) ? 'H:i:s' : 'Y-m-d';
					break;
		case 'FS':	$mode = 'Y-m-d H:i:s';
					break;
		case 'FI':	$mode = 'Y-m-d H:i';
					break;
		case 'FD':	$mode = 'Y-m-d';
					break;
		default:	break;
	}
	return gmdate($mode, $timenum+$zone*3600);
}

//跳转地址
function global_GoToUrl($urlstr)
{
	header("Location: ".$urlstr);
	exit();
}

//高亮关键字
function global_Highlight($strall, $strshow)
{
	if (trim($strall)!='' && trim($strshow)!='')
	{
		$strshowarray = explode(' ', $strshow);
		$strshowmode = array();
		foreach ($strshowarray as $tempshow)
		{
			$tempshow = trim($tempshow);
			if ($tempshow!='')
			{
				$strshowmode[] = "/($tempshow)/i";
			}
		}
		if (count($strshowmode)>0)
		{
			$strall = preg_replace($strshowmode, "<span class=\"highlight\">\${0}</span>", $strall);
		}
	}
	return $strall;
}

//数字化变量
function global_Intval($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_Intval($val);
		}
	}
	else
	{
		$string = intval(trim($string));
	}
	return $string;
}

//检查是否合法时间
function global_IsDate($ymd, $sep = '-')
{
	if (!empty($ymd))
	{
		@list($year, $month, $day) = explode($sep, $ymd);
		return @checkdate($month, $day, $year);
	}
	else
	{
		return FALSE;
	}
}

//检查是否合法email
function global_IsEmail($email)
{
	return strlen($email)>6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//检查是否手机
function global_IsMobile($mobile)
{
	return preg_match("/^1[0-9]{10}$/", $mobile);
}

//密码运算
function global_Key($txt, $authkey)
{
	$authkey = md5($authkey);
	$txtlen = strlen($txt);
	$authkeylen = strlen($authkey);
	$ctr = 0;
	$tmp = '';
	for ($i=0; $i<$txtlen; $i++)
	{
		if ($ctr == $authkeylen)
		{
			$ctr = 0;
		}
		$tmp .= substr($txt, $i, 1) ^ substr($authkey, $ctr, 1);
		$ctr++;
	}
	return $tmp;
}

//改良MD5
function global_Md5($strVar)
{
	return ($strVar != '') ? md5('2-4-7,'.md5($strVar).',v-i-p') : '';
}

//分页函数
function global_Page($intnum, $intpernum, $intcurpage, $strlinkurl, $intshowlinks = 7, $intmaxpages = 0, $strsign = '@@')
{
	$intnum = abs(intval($intnum));
	$intpernum = max(1, intval($intpernum));
	$intcurpage = max(1, intval($intcurpage));
	$intshowlinks = max(1, intval($intshowlinks));
	$intmaxpages = abs(intval($intmaxpages));
	$returnarray = array();

	if ($intnum > 0)
	{
		$allabspages = $allpages = $startpage = $endpage = 0;
		$allabspages = ceil($intnum/$intpernum);
		$allpages = ($intmaxpages>0 && $intmaxpages<$allabspages) ? $intmaxpages : $allabspages;
		$intcurpage = ($intcurpage>$allpages) ? $allpages : $intcurpage;

		$startpage = $intcurpage-floor($intshowlinks/2);
		$endpage = $intcurpage+floor($intshowlinks/2);
		if ($startpage>0 && $endpage>$allpages)
		{
			$startpage = ($endpage-$allpages<$startpage) ? $startpage-$endpage+$allpages : 1;
			$endpage = $allpages;
		}
		elseif ($startpage<=0 && $endpage<=$allpages)
		{
			$endpage = ($endpage-$startpage+1<=$allpages) ? $endpage-$startpage+1 : $allpages;
			$startpage = 1;
		}
		elseif ($startpage<=0 && $endpage>$allpages)
		{
			$startpage = 1;
			$endpage = $allpages;
		}

		$returnarray['datanum'] = $intnum;
		$returnarray['pernum'] = $intpernum;
		$returnarray['pagenum'] = $allpages;
		$returnarray['curpage'] = $intcurpage;
		$returnarray['page'] = array();

		if ($strlinkurl!='')
		{
			$returnarray['prev'] = ($intcurpage>1) ? str_replace($strsign, $intcurpage-1, $strlinkurl) : '';
			$returnarray['first'] = ($startpage>1) ? str_replace($strsign, 1, $strlinkurl) : '';
			$returnarray['front'] = ($startpage>2) ? str_replace($strsign, ceil((1+$startpage)/2), $strlinkurl) : '';
			for ($i=$startpage; $i<=$endpage; $i++)
			{
				$returnarray['page'][$i] = str_replace($strsign, $i, $strlinkurl);
			}
			$returnarray['back'] = ($endpage<$allpages-1) ? str_replace($strsign, ceil(($endpage+$allpages)/2), $strlinkurl) : '';
			$returnarray['last'] = ($endpage<$allpages) ? str_replace($strsign, $allpages, $strlinkurl) : '';
			$returnarray['next'] = ($intcurpage<$allpages) ? str_replace($strsign, $intcurpage+1, $strlinkurl) : '';
			$returnarray['input'] = ($startpage>2 || $endpage<$allpages-1) ? 'onKeyDown="javascript:if(window.event.keyCode==13 && this.value!=\'\'){window.location=\''.str_replace($strsign, '\'+this.value+\'', $strlinkurl).'\';}"' : '';
		}
		else
		{
			$returnarray['prev'] = ($intcurpage>1) ? $intcurpage-1 : 0;
			$returnarray['first'] = ($startpage>1) ? 1 : 0;
			$returnarray['front'] = ($startpage>2) ? ceil((1+$startpage)/2) : 0;
			for ($i=$startpage; $i<=$endpage; $i++)
			{
				$returnarray['page'][$i] = $i;
			}
			$returnarray['back'] = ($endpage<$allpages-1) ? ceil(($endpage+$allpages)/2) : 0;
			$returnarray['last'] = ($endpage<$allpages) ? $allpages : 0;
			$returnarray['next'] = ($intcurpage<$allpages) ? $intcurpage+1 : 0;
			$returnarray['input'] = ($startpage>2 || $endpage<$allpages-1) ? 1 : 0;
		}
	}
	
	return $returnarray;
}

//js分页内容处理
function global_PageBreak($strContent)
{
	$returnstr = '';
	$strSign = '<hr />';
	$contentArray = explode($strSign, $strContent);
	$contentArrayNum = count($contentArray);
	if ($contentArrayNum <= 1)
	{
		$returnstr .= '<div id="content_show_1">'.$strContent.'</div>';
	}
	else
	{
		$returnstr .= '<a name="pageanchor"></a>';
		foreach ($contentArray as $tempkey => $tempvalue)
		{
			$returnstr .= '<div id="content_show_'.($tempkey+1).'" class="hidden">'.$tempvalue.'</div>';
		}
		$returnstr .= '<div id="content_page"></div><script type="text/javascript">common_ContentShow('.$contentArrayNum.', 1);</script>';
	}
	return $returnstr;
}

//生成随机字符
function global_Random($length, $numeric = 0)
{
	PHP_VERSION<'4.2.0' and mt_srand((double)microtime() * 1000000);
	if ($numeric)
	{
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	}
	else
	{
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++)
		{
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

//检查数组中是否有某个值
//$intarray 返回数组格式 0:否 1:是
function global_SearchArray($str, $array, $key = '', $intarray = 0)
{
	$returnarray = array();
	foreach ($array as $k => $v)
	{
		if ($key=='')
		{
			if ($v==$str)
			{
				if ($intarray==0)
				{
					return $k;
				}
				else
				{
					$returnarray[] = $k;
				}
			}
		}
		else
		{
			if (isset($v[$key]) && $v[$key]==$str)
			{
				if ($intarray==0)
				{
					return $k;
				}
				else
				{
					$returnarray[] = $k;
				}
			}
		}
	}
	if ($intarray==0)
	{
		return FALSE;
	}
	else
	{
		return $returnarray;
	}
}

//根据标记找目录数组键值
function global_SearchMenu($strSign)
{
	global $webcache;
	if (isset($webcache['menu']))
	{
		foreach ($webcache['menu'] as $key => $value)
		{
			if ($value['wi_key']==$strSign)
			{
				return array($key);
			}
			if (!empty($value['sublayer']))
			{
				foreach ($value['sublayer'] as $subkey => $subvalue)
				{
					if ($subvalue['wi_key']==$strSign)
					{
						return array($key, $subkey);
					}
				}
			}
		}
	}
	return array();
}

//设置cookie
function global_SetCookie($var, $value, $life = 0, $prefix = 1)
{
	global $webconfig, $webserver, $_SERVER;
	setcookie(($prefix ? $webconfig['cookiepre'] : '').$var, $value,
		$life ? $webserver['timestamp']+$life : 0, $webconfig['cookiepath'],
		$webconfig['cookiedomain'], $_SERVER['SERVER_PORT']==443 ? 1 : 0);
}

//显示提示信息
function global_ShowMessage($showmessage, $urlforward = '', $extra = '', $morelink = array())
{
	global $db, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig;

	$webglobal['showmessage'] = $showmessage;
	$webglobal['smgurlforward'] = $urlforward;
	$webglobal['smgextra'] = $extra;
	$webglobal['morelink'] = $morelink;
	$webglobal['isautojump'] = FALSE;
	if ($webglobal['smgurlforward']!='' && $webglobal['smgextra']!='STOP')
	{
		$webglobal['isautojump'] = TRUE;
		$webglobal['htmlhead'][] = '<meta http-equiv="refresh" content="3;url='.$webglobal['smgurlforward'].'" />';
	}
	template_Display("showmessage");
	exit();
}

//去除变量前后的空格
function global_Trim($string)
{
	if (is_array($string))
	{
		foreach ($string as $key => $val)
		{
			$string[$key] = global_Trim($val);
		}
	}
	else
	{
		$string = trim($string);
	}
	return $string;
}

//获取用户权限列表
function global_getPurviewListData($strPurview = '') {
	global $db, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig;

	$tempResult = array();

	$query = $db->query("SELECT * FROM {$webconfig['dbpre']}purview ORDER BY upid, `order` DESC, id ASC");
	while ($tempData = $db->FetchArray($query)) {
		if ($tempData['upid'] > 0) {
			$tempIsCheck = ($strPurview != '') ? global_CheckHaveVar($strPurview, $tempData['id']) : FALSE;
			$tempData['checked'] = $tempIsCheck;
			$tempResult[$tempData['upid']]['listid'][] = $tempData['id'];
			$tempResult[$tempData['upid']]['list'][$tempData['id']] = $tempData;
		} else {
			$tempData['listid'] = array();
			$tempData['list'] = array();
			$tempResult[$tempData['id']] = $tempData;
		}
	}

	return $tempResult;
}

//格式化链接地址
function buildURLForModule($page = '', $args = array()) {
	if (!$page) {
		$page = defined('PAGESCRIPT') ? PAGESCRIPT : 'index';
	}
	$page = basename($page, '.php');
	$returnUrl = WEBURLPATH . "/".$page.".php?".http_build_query($args);
	$returnUrl = str_replace('%40%40', '@@', $returnUrl);

	return $returnUrl;
}

//兼容的json_encode函数
if (!function_exists('json_encode'))
{
	function format_json_value(&$value)
	{
		if(is_bool($value)) {
			$value = $value?'true':'false';
		}elseif(is_int($value)) {
			$value = intval($value);
		}elseif(is_float($value)) {
			$value = floatval($value);
		}elseif(defined($value) && $value === null) {
			$value = strval(constant($value));
		}elseif(is_string($value)) {
			$value = '"'.addslashes($value).'"';
		}
		return $value;
	}

	function json_encode($data)
	{
		if(is_object($data)) {
			//对象转换成数组
			$data = get_object_vars($data);
		}else if(!is_array($data)) {
			// 普通格式直接输出
			return format_json_value($data);
		}
		// 判断是否关联数组
		if(empty($data) || is_numeric(implode('',array_keys($data)))) {
			$assoc  =  false;
		}else {
			$assoc  =  true;
		}
		// 组装 Json字符串
		$json = $assoc ? '{' : '[' ;
		foreach($data as $key=>$val) {
			if(!is_null($val)) {
				if($assoc) {
					$json .= "\"$key\":".json_encode($val).",";
				}else {
					$json .= json_encode($val).",";
				}
			}
		}
		if(strlen($json)>1) {// 加上判断 防止空数组
			$json  = substr($json,0,-1);
		}
		$json .= $assoc ? '}' : ']' ;
		return $json;
	}
}

function getThumbnails($image = '', $type = 'small') {
	if ($image) {
		$dirName = dirname($image);
		$fileName = basename($image);
		if ($type) {
			$fileName = $type . '_' . $fileName;
		}

		return $dirName . '/' . $fileName;
	}

	return '';
}

/*
<attributes>
    <iterm>col:分多少列显示（默认为单列），5.3版中本属性可以通过多种方式进行多行显示</iterm>
    <iterm>row:返回文档列表总数</iterm> 
    <iterm>typeid:栏目ID,在列表模板和档案模板中一般不需要指定，在首页模板中允许用","分开表示多个栏目</iterm>
    <iterm>getall:在没有指定这属性的情况下,在栏目页、文章页模板,不会获取以","分开的多个栏目的下级子类</iterm>
    <iterm>titlelen:标题长度 等同于titlelength</iterm>
    <iterm>infolen:表示内容简介长度 等同于infolength</iterm>
    <iterm>imgwidth:缩略图宽度</iterm>
    <iterm>imgheight:缩略图高度</iterm>
    <iterm>listtype: 栏目类型 image含有缩略图 commend推荐</iterm>
    <iterm>orderby:文档排序方式</iterm>
    <iterm>keyword:含有指定关键字的文档列表，多个关键字用","分</iterm>
    <iterm>innertext:单条记录样式</iterm>
    <iterm>aid:指定文档ID</iterm>
    <iterm>idlist:提取特定文档（文档ID</iterm>
    <iterm>channelid:频道ID</iterm>
    <iterm>limit:（起始ID从0开始）表示限定的记录范围（如：limit='1,2'  表示从ID为1的记录开始，取2条记录</iterm>
    <iterm>flag:自定义属性值：头条[h]推荐[c]图片[p]幻灯[f]滚动[s]跳转[j]图文[a]加粗[b]</iterm>
    <iterm>noflag:同flag，但这里是表示不包含这些属性</iterm>
    <iterm>orderway:值为 desc 或 asc ，指定排序方式是降序还是顺向排序，默认为降序</iterm>
    <iterm>subday:表示在多少天以内的文档</iterm>
</attributes>
*/
function getArcList($attributes = array()) {
	global $newsCategoryDataModel, $db, $webconfig ;

	$filters = array();
	$orderbys = array();
	$limit = 0;

	if (isset($attributes['titlelen'])) {
		
	}
	$titlelen = isset($attributes['titlelen']) ? $attributes['titlelen'] : 30;
	$row = isset($attributes['row']) ? $attributes['row'] : 10;
	$infolen = isset($attributes['infolen']) ? $attributes['infolen'] : 160;
	$imgwidth = isset($attributes['imgwidth']) ? $attributes['imgwidth'] : 120;
	$imgheight = isset($attributes['imgheight']) ? $attributes['imgheight'] : 120;
	$listtype = isset($attributes['listtype']) ? $attributes['listtype'] : 'all';
	$arcid = isset($attributes['arcid']) ? $attributes['arcid'] : 0;
	$channelid = isset($attributes['channel']) ? $attributes['channel'] : 0;

	$orderby = isset($attributes['orderby']) ? $attributes['orderby'] : 'default';
	$orderWay = isset($attributes['orderWay']) ? $attributes['orderWay'] : 'desc';
	$subday = isset($attributes['subday']) ? $attributes['subday'] : 0;
	$pagesize = isset($attributes['pagesize']) ? $attributes['pagesize'] : 0;
	$limit = isset($attributes['limit']) ? $attributes['limit'] : '';
	$getall = isset($attributes['getall']) ? $attributes['getall'] : 0;
	$keyword = isset($attributes['keyword']) ? trim($attributes['keyword']) : '';

	$line = $row;

	$orderby = strtolower($orderby);
	$keyword = trim($keyword);

	$writer = isset($attributes['writer']) ? $attributes['writer'] : '';
	$att = isset($attributes['flag']) ? $attributes['flag'] : '0';
	$idlist = isset($attributes['idlist']) ? $attributes['idlist'] : '';

	$typeid = isset($attributes['typeid']) ? $attributes['typeid'] : '';
	$getall = isset($attributes['getall']) ? $attributes['getall'] : 0;
	$noflag = isset($attributes['noflag']) ? $attributes['noflag'] : '';
	
	$brand = isset($attributes['brand']) ? intval($attributes['brand']) : 0;

	if($att=='0') $att='';
	if($att=='3') $att='f';
	if($att=='1') $att='h';

	if (!$idlist) {
		if($subday > 0) {
			$ntime = gmmktime(0, 0, 0, gmdate('m'), gmdate('d'), gmdate('Y'));
			$limitday = $ntime - ($subday * 24 * 3600);
			$filters[] = " arc.showtime  > $limitday ";
		}
		//关键字条件
		if($keyword!='') {
			$keyword = str_replace(',', '|', $keyword);
			$filters[] = " CONCAT(arc.title,arc.keywords) REGEXP '$keyword'";
		}

		//文档属性
		if(preg_match('/commend/i', $listtype)) $filters[] = " FIND_IN_SET('c', arc.flag)>0  ";
		if(preg_match('/image/i', $listtype)) {
			$filters[] = " FIND_IN_SET('p', arc.flag)>0  ";
		}
		if($att != '') {
			$flags = explode(',', $att);
			for($i=0; isset($flags[$i]); $i++) {
				$filters[] = " FIND_IN_SET('{$flags[$i]}', arc.flag)>0 ";
			}
		}

		if ($brand > 0) {
			$filters[] = " arc.brand_id = {$brand} ";
		}

		if (in_array($channelid, array(1, 2))) {
			$filters[] = " arc.channel = {$channelid} ";
		}
		if(!empty($typeid) && $typeid != 'top') {
			//指定了多个栏目时，不再获取子类的id
			if(preg_match('#,#', $typeid)) {
				//指定了getall属性或主页模板例外
				if($getall) {
					$typeids = explode(',', $typeid);
					$typeidss = array();
					foreach($typeids as $ttid) {
						$typeidss[] = $newsCategoryDataModel->getChildIds($ttid, 0, true);
					}
					$typeidStr = join(',', $typeidss);
					$typeidss = explode(',', $typeidStr);
					$typeidssok = array_unique($typeidss);
					$typeid = implode(',', $typeidssok);
				}
				$filters[] = " arc.news_category_id IN ($typeid) ";
			} else {
				$filters[] = " arc.news_category_id IN (". implode(',', $newsCategoryDataModel->getChildIds($typeid, 0, true)) .") ";
			}
		}

		if(!empty($noflag)) {
			if(!preg_match('#,#', $noflag)) {
				$filters[] = " FIND_IN_SET('$noflag', arc.flag)<1 ";
			} else {
				$noflags = explode(',', $noflag);
				foreach($noflags as $noflag) {
					if(trim($noflag)=='') continue;
					$filters[] = " FIND_IN_SET('$noflag', arc.flag)<1 ";
				}
			}
		}
	}
	$filters[] = ' arc.arcrank > -1 ';

	//文档排序的方式
	$ordersql = '';
    if($orderby=='hot' || $orderby=='click') $ordersql = " ORDER BY arc.click $orderWay";
    else if($orderby == 'sortrank' || $orderby=='pubdate') $ordersql = " ORDER BY arc.sortrank $orderWay";
    else if($orderby == 'id') $ordersql = "  ORDER BY arc.id $orderWay";
    else if($orderby == 'near') $ordersql = " ORDER BY ABS(arc.id - ".$arcid.")";
    else if($orderby == 'lastpost') $ordersql = "  ORDER BY arc.lastpost $orderWay";
    else if($orderby == 'scores') $ordersql = "  ORDER BY arc.scores $orderWay";
    else if($orderby == 'rand') $ordersql = "  ORDER BY rand()";
    else $ordersql = " ORDER BY arc.sortrank $orderWay"; 

    //limit条件
    $limit = trim(preg_replace('#limit#is', '', $limit));
    if($limit!='') $limitsql = " LIMIT $limit ";
    else $limitsql = " LIMIT 0,$line ";
	
	$orwhere = '';
    if($filters) {
		$orwhere = " WHERE " . implode(' AND ', $filters);
    }

	//指定了id或使用缓存中的id
	if($idlist != '') {
		$sql = "SELECT arc.*,tp.id as tp_id, tp.name as tp_name, tp.seotitle as tp_seotitle, tp.keywords as tp_keywords 
             FROM {$webconfig['dbpre']}news arc left join {$webconfig['dbpre']}news_category tp on arc.news_category_id=tp.id
          WHERE arc.id in($idlist) AND arc.arcrank>-1 $ordersql ";
    } else {
		$sql = "SELECT arc.*,tp.id as tp_id, tp.name as tp_name, tp.seotitle as tp_seotitle, tp.keywords as tp_keywords
        FROM {$webconfig['dbpre']}news arc LEFT JOIN {$webconfig['dbpre']}news_category tp on arc.news_category_id=tp.id
        $orwhere $ordersql $limitsql";
	}

	$tempResult = array();
	$autoindex = 0;
	$query = $db->Query($sql);
	while ($row = $db->FetchArray($query)) {
		$autoindex++;
		$row['info'] = $row['infos'] = global_CutStr($row['description'], $infolen);
		//$row['title'] = SpHtml2Text($row['title']);
		$row['filename'] = $row['arcurl'] = WEBURLPATH . '/news.php?action=article&id=' . $row['id'];

		$row['typeurl'] = WEBURLPATH . '/news.php?action=type&id=' . $row['tp_id'];

		if($row['litpic'] == '-' || $row['litpic'] == '') {
			$row['litpic'] = WEBURLPATH.'/images/defaultpic.gif';
		} elseif (!preg_match("#^http:\/\/#i", $row['litpic'])) {
			$row['litpic'] = WEBURLPATH.$row['litpic'];
		}

		$row['picname'] = $row['litpic'];
		$row['stime'] = global_FormatTime($row['showtime'], 'FD');
		$row['typelink'] = "<a href='".$row['typeurl']."'>".$row['tp_name']."</a>";
		$row['image'] = "<img src='".$row['picname']."' border='0' width='$imgwidth' height='$imgheight' alt='".preg_replace("#['><]#", "", $row['title'])."'>";
		$row['imglink'] = "<a href='".$row['filename']."'>".$row['image']."</a>";
		$row['fulltitle'] = $row['title'];
		$row['title'] = global_CutStr($row['title'], $titlelen);
		if($row['color']!='') $row['title'] = "<font color='".$row['color']."'>".$row['title']."</font>";
		if(preg_match('#b#', $row['flag'])) $row['title'] = "<strong>".$row['title']."</strong>";
		//$row['title'] = "<b>".$row['title']."</b>";
		$row['textlink'] = "<a href='".$row['filename']."'>".$row['title']."</a>";
		$row['autoindex'] = $autoindex;
		
		$tempResult[$row['id']] = $row;
	}

	return $tempResult;
}
